package com.jinyi.wwdeng.ui.user.act

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.provider.MediaStore
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.jinyi.base.utils.log.HHLog
import com.jinyi.lib_baseadapter.BGAOnItemChildClickListener
import com.jinyi.wwdeng.App
import com.jinyi.wwdeng.R
import com.jinyi.wwdeng.databinding.ActUserFeedbackBinding
import com.jinyi.wwdeng.databinding.ItemQuestionBinding
import com.jinyi.wwdeng.network.ApiService
import com.jinyi.wwdeng.network.HttpBaseParams.addCommonParams
import com.jinyi.wwdeng.pro.ProMvpAct
import com.jinyi.wwdeng.ui.user.adapter.UserFeedbackContactAdapter
import com.jinyi.wwdeng.ui.user.adapter.UserFeedbackImageAdapter
import com.jinyi.wwdeng.ui.user.contract.UserFeedbackContract
import com.jinyi.wwdeng.ui.user.impl.UserFeedbackPresenterImpl
import com.jinyi.wwdeng.utils.event.TrackEventType
import com.jinyi.wwdeng.utils.event.TrackEventUtils
import com.jinyi.wwdeng.utils.imagecovert.ImageConvert
import id.zelory.compressor.Compressor
import id.zelory.compressor.constraint.destination
import id.zelory.compressor.constraint.quality
import id.zelory.compressor.constraint.resolution
import id.zelory.compressor.constraint.size
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.io.File


/**
 * JinYiTest
 * @Author wwdeng
 * @CreateTime: 2024/4/24 19:56
 * @Annotation：我的账户
 */
class UserFeedbackAct: ProMvpAct<UserFeedbackContract.View, UserFeedbackPresenterImpl>(), UserFeedbackContract.View {

    lateinit var binding: ActUserFeedbackBinding
    //联系方式列表
    var mContactAdapter: UserFeedbackContactAdapter? = null
    //反馈类型列表
    var typeList: ArrayList<JSONObject>? = null
    //图片列表
    var mImgAdapter: UserFeedbackImageAdapter? = null

    //图片压缩后存储的临时文件
    var destinationDirectory: File? = null
    //图片选择
    private lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>

    override fun getRootView(): View {
        binding = ActUserFeedbackBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun createPresenter(): UserFeedbackPresenterImpl {
        return UserFeedbackPresenterImpl()
    }

    override fun initView() {
        initPresenter()
        setTitleBarVisibility(View.VISIBLE)
        setTextTitle(getString(R.string.help_feedback))
        setTextTitleGravity(Gravity.CENTER)
        setRightBtnVisibility(View.GONE)

        initRecyclerView()
        initImageRecyclerView()
        binding.tvLength.text = "0/1000"

        // 1-注册图库组件
        pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri != null) {
                // 图片处理
                HHLog.e("uri.path>>>>>>>>>>>>>>${uri.path}")
                ImageConvert.covert(context = this, uri = uri) { localPath, bitmap ->
                    HHLog.e(">>>>>>>>>>>>>localPath: $localPath")
                    if (localPath != null){
                        //最多只能选三张
                        if (mImgAdapter!!.itemCount == 3){
                            mImgAdapter!!.removeItem(0)
                        }
                        val imgObj = JSONObject()
                        imgObj.put("isDefault",false)
                        imgObj.put("imgPath",localPath)
                        mImgAdapter!!.addLastItem(imgObj)

                        presenter.uploadImageAction(localPath)
                    }
                }

            } else {
                HHLog.e("No media selected")
            }
        }
    }

    override fun initListener() {
        //联系客服
        rootViewBinding.ivFun.setOnClickListener {
            onIntent(UserFeedbackAct::class.java)
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_CUSTOMER,"UserFeedback Page")
        }
        //输入框监听
        binding.editRemark.addTextChangedListener(IEditChangeListener)
        binding.editRemark.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus && binding.editRemark.text.toString().isNotEmpty()){
                TrackEventUtils.logEvent(TrackEventType.FORM.FORM_USER_FEEDBACK_DESCRIBE,binding.editRemark.text.toString())
            }
        }
        //提交
        binding.btnSubmit.setOnClickListener {
            //问题类型
            if (getSelectTypeItem() == null){
                showToast(getString(R.string.please_select_question_type))
                return@setOnClickListener
            }
            val remark = binding.editRemark.text.toString()
            if (remark.isEmpty()){
                showToast(getString(R.string.briefly_describe_your_problem_demand))
                return@setOnClickListener
            }
            showLoading("")
            val params = JSONObject().addCommonParams().apply {
                put("path", ApiService.API_PATH.API_PATH_FEEDBACK_SUBMIT)
                put("type",getSelectTypeItem()!!.optString("value"))//反馈类型
                put("opinion",remark)//反馈内容
            }
            presenter.submitFeedbackAction(params)
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_USER_FEEDBACK_SUBMIT,"")
        }
    }

    override fun initData() {
        presenter.loadContactListAction()
        presenter.loadQuestionTypeListAction()

        val imgObj = JSONObject()
        imgObj.put("isDefault",true)
        mImgAdapter!!.addFirstItem(imgObj)
    }

    /**
     * 初始化联系方式列表
     */
    private fun initRecyclerView() {
        binding.recyclerView.setHasFixedSize(false)
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        mContactAdapter = UserFeedbackContactAdapter(binding.recyclerView)
        binding.recyclerView.adapter = mContactAdapter!!
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        mContactAdapter!!.setOnItemChildClickListener(BGAOnItemChildClickListener { parent, childView, position ->
            val item = mContactAdapter!!.getItem(position)
            when(childView.id){
                R.id.btnCopy -> {//复制
                    onCopyAction(item)
                }
                R.id.btnDial -> {//拨号
                    if (XXPermissions.isGranted(this, Permission.CALL_PHONE)){
                        onCallAction(item)
                    } else {
                        XXPermissions.with(this)
                            .permission(Permission.CALL_PHONE)
                            .request(object: OnPermissionCallback {
                                override fun onGranted(p0: MutableList<String>, p1: Boolean) {
                                    TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_PERMISSION_SYSTEM_AGREE,Permission.CALL_PHONE)
                                    onCallAction(item)
                                }
                                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                                    TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_PERMISSION_SYSTEM_DENY,Permission.CALL_PHONE)
                                    XXPermissions.startPermissionActivity(this@UserFeedbackAct,Permission.CALL_PHONE)
                                }
                            })
                    }
                }
            }
        })
    }

    /**
     * 初始化图片列表
     */
    private fun initImageRecyclerView() {
        binding.rvImgs.setHasFixedSize(false)
        binding.rvImgs.isNestedScrollingEnabled = false
        binding.rvImgs.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = RecyclerView.HORIZONTAL
        binding.rvImgs.layoutManager = layoutManager
        mImgAdapter = UserFeedbackImageAdapter(binding.rvImgs)
        binding.rvImgs.adapter = mImgAdapter!!
        binding.rvImgs.itemAnimator = DefaultItemAnimator()
        mImgAdapter!!.setOnItemChildClickListener(BGAOnItemChildClickListener { parent, childView, position ->
            val item = mImgAdapter!!.getItem(position)
            when(childView.id){
                R.id.ivDelete -> {//删除
                    if (!item.optBoolean("isDefault")){
                        mImgAdapter!!.removeItem(position)

                        //是否需要添加默认图片
                        var isAddDefault = true
                        for (i in 0..<mImgAdapter!!.itemCount){
                            if (mImgAdapter!!.getItem(i).optBoolean("isDefault")){
                                isAddDefault = false
                                break
                            }
                        }
                        if (isAddDefault){
                            val imgObj = JSONObject()
                            imgObj.put("isDefault",true)
                            mImgAdapter!!.addFirstItem(imgObj)
                        }
                    }
                }
                R.id.ivImage -> {//选择图片
                    if (item.optBoolean("isDefault")){
                        hasRequestPermissions()
                    }
                }
            }
        })
    }


    private val IEditChangeListener = object: TextWatcher{
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }
        override fun afterTextChanged(s: Editable?) {
            val textLength = s!!.length
            binding.tvLength.text = "$textLength/1000"
        }
    }

    /**
     * 设置问题类型列表
     */
    private fun setQuestionTypeList(){
        binding.flexboxLayout.removeAllViews()
        for (i in 0..< typeList!!.size) {
            val item = typeList!![i]
            val itemBinding = ItemQuestionBinding.inflate(layoutInflater)
            itemBinding.tvTitle.text = item.optString("title")
            if (item.optBoolean("isSelect")){
                itemBinding.tvTitle.setTextColor(ContextCompat.getColor(this,R.color.color_021e00))
                itemBinding.tvTitle.setBackgroundResource(R.drawable.base_circle_fill_9fe76f)
            } else {
                itemBinding.tvTitle.setTextColor(ContextCompat.getColor(this,R.color.color_6e6e6e))
                itemBinding.tvTitle.setBackgroundResource(R.drawable.base_circle_fill_f8f8f8)
            }
            binding.flexboxLayout.addView(itemBinding.root)
            itemBinding.tvTitle.setOnClickListener {
                if (item.optBoolean("isSelect")){
//                    item.put("isSelect",false)
//                    setQuestionTypeList()
                    return@setOnClickListener
                }
                for (index in 0..< typeList!!.size){
                    val obj = typeList!![index]
                    if (index == i){
                        obj.put("isSelect",true)
                        TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_USER_FEEDBACK_QUESTION_TYPE,obj.optString("title"))
                    } else {
                        obj.put("isSelect",false)
                    }
                }
                setQuestionTypeList()
            }
        }
    }

    /**
     * 获取选择的问题类型
     */
    private fun getSelectTypeItem(): JSONObject?{
        var selectItem: JSONObject? = null
        for (i in 0..<typeList!!.size){
            val obj = typeList!![i]
            if (obj.optBoolean("isSelect")){
                selectItem = obj
                break
            }
        }
        return selectItem
    }

    /**
     * 设置联系方式列表
     */
    override fun showContactList(contactList: ArrayList<JSONObject>) {
        mContactAdapter!!.data = contactList
    }

    /**
     * 设置意见反馈问题类型列表
     */
    override fun showQuestionTypeList(dataList: ArrayList<JSONObject>) {
        if (typeList == null){
            typeList = arrayListOf()
        }
        typeList!!.clear()
        typeList!!.addAll(dataList)
        setQuestionTypeList()
    }

    /**
     * 图片上传成功，需要删除临时文件
     */
    override fun showUploadImageSuccess(imgUrl: String) {
        TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_USER_FEEDBACK_UPLOAD_IMAGE,imgUrl)
        if (destinationDirectory != null && destinationDirectory!!.isFile){
            destinationDirectory!!.delete()
        }
    }

    /**
     * 显示反馈提交成功
     */
    override fun showSubmitSuccess() {
        finish()
    }

    /**
     * 复制
     */
    private fun onCopyAction(item: JSONObject){
        val type = item.optString("type")
        TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_USER_FEEDBACK_COPY,type + "：" + item.optString("value"))
        // 获取剪贴板管理器
        val clipboardManager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        // 创建一个 ClipData 对象，将要复制的文本放入其中
        val clipData = ClipData.newPlainText("label", item.optString("value"))
        // 将 ClipData 对象放入剪贴板
        clipboardManager.setPrimaryClip(clipData)
        showToast(getString(R.string.copy_success))
    }

    /**
     * 拨号
     */
    private fun onCallAction(item: JSONObject){
        val type = item.optString("type")
        TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_USER_FEEDBACK_DIAL,type + "：" + item.optString("value"))
        val callIntent = Intent(Intent.ACTION_DIAL)
        callIntent.setData(Uri.parse("tel:${item.optString("value")}"))
        startActivity(callIntent)
    }

    /**
     * 申请权限
     */
    private fun hasRequestPermissions(){
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
//        if (XXPermissions.isGranted(this, Permission.READ_MEDIA_IMAGES)){
//            onOpenAlbum()
//        } else {
//            XXPermissions.with(this)
//                // 申请多个权限
//                .permission(Permission.READ_MEDIA_IMAGES)
//                .request(object: OnPermissionCallback {
//                    override fun onGranted(p0: MutableList<String>, p1: Boolean) {
//                        TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_PERMISSION_SYSTEM_AGREE,Permission.READ_MEDIA_IMAGES)
//                        onOpenAlbum()
//                    }
//                    override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
//                        TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_PERMISSION_SYSTEM_DENY,Permission.READ_MEDIA_IMAGES)
//                        XXPermissions.startPermissionActivity(this@UserFeedbackAct,Permission.READ_MEDIA_IMAGES)
//                    }
//                })
//        }
    }

    /**
     * 打开相册
     */
    private fun onOpenAlbum(){
        val intent = Intent(Intent.ACTION_PICK)
        intent.setType("image/*")
        openAlbumResultLauncher.launch(intent)
    }

    /**
     * 相册选择照片
     */
    private val openAlbumResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            RESULT_OK -> {
                val uri = result.data!!.data
                val imgPath = getRealPathFromURI(uri!!)
                HHLog.e("文件路径>>>>>>>>>>>>>>$imgPath")
                if (imgPath != null){
                    compressImage(imgPath)
                    //最多只能选三张
                    if (mImgAdapter!!.itemCount == 3){
                        mImgAdapter!!.removeItem(0)
                    }
                    val imgObj = JSONObject()
                    imgObj.put("isDefault",false)
                    imgObj.put("imgPath",imgPath)
                    mImgAdapter!!.addLastItem(imgObj)
                }
            }
        }
    }

    /**
     * 根据uri获取文件路径
     */
    private fun getRealPathFromURI(contentURI: Uri): String? {
        val result: String?
        val cursor = contentResolver.query(contentURI, null, null, null, null)
        if (cursor == null) {
            result = contentURI.path
        } else {
            cursor.moveToFirst()
            val idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
            result = cursor.getString(idx)
            cursor.close()
        }
        return result
    }

    /**
     * 压缩图片
     */
    private fun compressImage(imgPath: String) {
        showLoading("")
        //压缩后的文件
//        val filePath = Environment.getExternalStorageDirectory().toString() + File.separator + "DCIM/Camera/";
        val filePath = App.instance().filesDir.absolutePath
        destinationDirectory = File(filePath,"${System.currentTimeMillis()}.jpg")
        File(imgPath).let { imageFile ->
            lifecycleScope.launch {
                // Default compression
                val compressedImageFile = Compressor.compress(this@UserFeedbackAct, imageFile) {
                    destination(destinationDirectory!!)
                    resolution(1280, 720)
                    quality(80)
                    size(1_097_152) // 1 MB
                }
                compressedImageFile.let {
                    HHLog.e("压缩完成>>>>>>>>>>>"+it.absolutePath)
                    presenter.uploadImageAction(it.absolutePath)
                }
            }
        }
    }


    fun getPathFromUri(uri: Uri?): String? {
        var cursor: Cursor? = null
        var path: String? = null
        try {
            // 只查询媒体数据的数据列
            val projection = arrayOf(MediaStore.MediaColumns.DATA)
            cursor = this.contentResolver.query(uri!!, projection, null, null, null)
            if (cursor != null && cursor.moveToFirst()) {
                // 获取数据列的索引，一般只有一个数据列，即索引为0
                val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)
                // 获取数据列的数据，即文件的真实路径
                path = cursor.getString(columnIndex)
            }
        } catch (e: Exception) {
            // 处理异常情况
        } finally {
            cursor?.close()
        }
        return path
    }

    override fun onRequestFinish() {
        super.onRequestFinish()
        hideLoading()
    }

    override fun onStart() {
        super.onStart()
        TrackEventUtils.logEvent(TrackEventType.PAGE.PAGE_USER_FEEDBACK_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        TrackEventUtils.logEvent(TrackEventType.PAGE.PAGE_USER_FEEDBACK_END,"")
    }
}